package com.single.weblearn.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.single.weblearn.dao.UserDao;
import com.single.weblearn.json.Result;
import com.single.weblearn.meta.User;

@Controller
public class LoginController {
	private UserDao u_dao;

	@Autowired
	public LoginController(UserDao u_dao) {
		this.u_dao = u_dao;
	}
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(){
		return "login";
	}
	
	@RequestMapping(value = "/api/login", method = RequestMethod.POST)
	public ResponseEntity<Result> login(@RequestParam("userName") String username,
			@RequestParam("password") String password,HttpServletRequest request) {		
		if (password.equals(this.u_dao.valiateUser(username))) {
			User user = this.u_dao.getUserByname(username);
			HttpSession session = request.getSession();
			session.setAttribute("user", user);
			Result result = new Result();
			result.setMessage("登录成功");
			result.setResult(true);
			result.setCode(200);
			return new ResponseEntity<Result>(result, HttpStatus.OK);
		}else{
			Result result = new Result();
			result.setMessage("登录失败");
			result.setResult(false);
            result.setCode(400);
			return new ResponseEntity<Result>(result, HttpStatus.BAD_REQUEST);
		}
	}
}
